package com.ogawa.jopai.devicemanage.viewmodel

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.ogawa.base.base.BaseViewModel
import com.ogawa.base.bean.LoadState
import com.ogawa.base.constants.Constants.Companion.NET_DEF_PLATFORM
import com.ogawa.projectcommon.utils.dataConvert
import com.ogawa.projectcommon.utils.launch
import com.ogawa.jopai.devicemanage.bean.*
import com.ogawa.projectcommon.network.RetrofitManager
import com.ogawa.jopai.devicemanage.service.MassageApiService
import com.ogawa.projectcommon.dboperation.OperationDB
import com.ogawa.projectcommon.utils.ProjectSpUtils
import kotlinx.coroutines.cancel

open class DeviceManageViewModel : BaseViewModel() {
    internal val beanList = MutableLiveData<List<UserDeviceBean>>()
    internal  val mDeleteUserDeviceResponse = MutableLiveData<DeleteUserDeviceResponse>()
    internal  val mDeviceShareResponse = MutableLiveData<DeviceShareResponse>()
    internal  val mChangeUserDeviceInfoResponse = MutableLiveData<ChangeUserDeviceInfoResponse>()
    internal  val mGetChairStatusResponse = MutableLiveData<GetChairStatusResponse>()
    internal val mGetDeviceShareResponseList = MutableLiveData<List<GetDeviceShareResponse>>()
    internal  val mGetChairStatusColResponse = MutableLiveData<List<GetChairStatusColResponse>>()

    //获取设备分享消息
    fun getDeviceShare() {
        launch({
            val userInfo = ProjectSpUtils.getUserInfo()
            loadState.value = LoadState.Loading("")
            mGetDeviceShareResponseList.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                .getDeviceShare(userInfo.user.id)
                .dataConvert()

            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }


    /*
    获取用户设备列表
     */
    fun getUserDevice() {
        launch({
            loadState.value = LoadState.Loading("")
            val userInfo = ProjectSpUtils.getUserInfo()
            if (userInfo.isVisitor){
                val queryEntityUserDeviceByName =
                    OperationDB().queryEntityUserDeviceByName(userInfo.user.id)
                val deviceBeans = ArrayList<UserDeviceBean>()
                queryEntityUserDeviceByName?.run {
                    for (item in this){
                        var mUserDeviceBean = UserDeviceBean()
                        mUserDeviceBean.id = item.id
                        mUserDeviceBean.deviceId = item.deviceId
                        mUserDeviceBean.imageSrc = item.imageSrc
                        mUserDeviceBean.name = item.deviceName
                        mUserDeviceBean.bluetoothName = item.bluetoothName
                        mUserDeviceBean.typeCode = item.typeCode
                        mUserDeviceBean.typeName = item.typeName
                        mUserDeviceBean.sn = item.deviceSN
                        mUserDeviceBean.readUuid = item.readUuid
                        mUserDeviceBean.writerUuid = item.writerUuid
                        mUserDeviceBean.peripheralUuid = item.peripheralUuid
                        mUserDeviceBean.androidUuid = item.androidUuid
                        mUserDeviceBean.iosUuid = item.iosUuid
                        mUserDeviceBean.status = item.status
                        mUserDeviceBean.label = item.label
                        mUserDeviceBean.quoteUserDeviceId = item.quoteUserDeviceId
                        mUserDeviceBean.createTime = item.createTime
                        deviceBeans.add(mUserDeviceBean)
                    }
                }
                beanList.value = deviceBeans
            }else{
                beanList.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                    .getUserDevice(NET_DEF_PLATFORM)
                    .dataConvert()
            }


            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }


    /*
    删除设备
     */
    fun userDevicesDelete(deviceId:String) {
        launch({
            loadState.value = LoadState.Loading("")
            val userInfo = ProjectSpUtils.getUserInfo()
            if (userInfo.isVisitor){
                val ret = DeleteUserDeviceResponse()
                OperationDB().deleteEntityUserDeviceBySn(deviceId)
                mDeleteUserDeviceResponse.value = ret
            }else {
                mDeleteUserDeviceResponse.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                    .userDevicesDelete(deviceId)
                    .dataConvert()
            }

            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }
    /*
    分享设备
     */
    fun deviceShare(shareRequest: DeviceShareRequest) {
        launch({
            loadState.value = LoadState.Loading("")
            mDeviceShareResponse.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                .deviceShare(shareRequest)
                .dataConvert()
            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }
    /*
   修改设备信息
    */
    fun changeUserDevices(deviceId: String, request: ChangeUserDeviceInfoRequest) {
        launch({
            loadState.value = LoadState.Loading("")

            val userInfo = ProjectSpUtils.getUserInfo()
            if (userInfo.isVisitor){
                val operationDB = OperationDB()
                val queryEntityUserDeviceByDeviceID =
                    operationDB.queryEntityUserDeviceByDeviceID(deviceId)
                if (queryEntityUserDeviceByDeviceID != null){
                    queryEntityUserDeviceByDeviceID.deviceName = request.name
                }
                operationDB.updateEntityUserDevice(queryEntityUserDeviceByDeviceID)
                mChangeUserDeviceInfoResponse.value = ChangeUserDeviceInfoResponse()
            }else{
                mChangeUserDeviceInfoResponse.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                    .changeUserDevices(deviceId, request)
                    .dataConvert()
            }


            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }
    /*
       按摩椅运行查询【根据MAC获取序列号】-准确
        */
    fun getChairStatus(param: String, isMac: String) {
        launch({
//            loadState.value = LoadState.Loading("")
            mGetChairStatusResponse.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                .getChairStatus(param, isMac)
                .dataConvert()
//            loadState.value = LoadState.Success("")
        }
            , {
//                loadState.value = LoadState.Fail(it.message ?: "")
                LogUtils.e("getChairStatus err : $param :  ${it.message}")
            }
            , {})
    }

    /*
      按摩椅运行查询【根据MAC获取序列号】-准确  sn  逗号隔开的字符串
       */
    fun getChairStatusCol(param: String) {
        launch({
            mGetChairStatusColResponse.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                    .getChairStatusCol(param)
                    .dataConvert()
        }
                , {
//                loadState.value = LoadState.Fail(it.message ?: "")
            LogUtils.e("getChairStatus err : $param :  ${it.message}")
        }
                , {})
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun onOnLifecycleEvent() {
        LogUtils.e("ON_DESTROY")
        viewModelScope.cancel()
    }

}
